//
//  OAuthViewController.swift
//  swift微博
//
//  Created by CC on 16/2/28.
//  Copyright © 2016年 CC. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {

    override func loadView() {
        self.view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        webView.backgroundColor = UIColor.whiteColor()
        
        setNavigationBar()
        
        let request = NSURLRequest(URL: NetWorkTool.sharedInstance.oauthLoginUrl())
        webView.loadRequest(request)
        
    }
    
    //设置导航栏
    func setNavigationBar(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }

    // MARK: - item点击方法
    func autoFill() {
        // 执行js代码,自动填充账号密码
        let js = "document.getElementById('userId').value='245806035@qq.com';document.getElementById('passwd').value='ccshuai3687936cc'"
        webView.stringByEvaluatingJavaScriptFromString(js)
        
    }
    
    func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    //MARK-懒加载webview
    lazy var webView : UIWebView = UIWebView()

}
//webView的协议方法：开始，结束加载时调用
extension OAuthViewController : UIWebViewDelegate{
    
    //// webView开始加载请求
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showInfoWithStatus("正在加载登录界面",maskType: SVProgressHUDMaskType.Black)
    }
    
    // webView加载完毕调用
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    // webView加载失败时调用
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.showErrorWithStatus("加载失败",maskType: SVProgressHUDMaskType.Black)
    }
    
    // webView询问我们是否要去加载某个请求: true去加载,false不加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL?.absoluteString
        // 通过?后面是code=表示点击了授权按钮,不是code=开头,点击的是取消按钮
        // 1.判断是否是回调地址开头.是回调地址开头,表示用点击的是授权或取消按钮
        if urlString!.hasPrefix(NetWorkTool.sharedInstance.redirect_uri) {
            // 判断点击的是授权还是取消
            // 截取url地址?后面的请求参数
            // query:?后面的请求参数
            let query = request.URL?.query
            print("query: \(query)")
            
            // 判断query是以code=开头表示点击的是 授权按钮, 其它的点击的是 取消 按钮
            let codeString = "code="
            if query!.hasPrefix(codeString) {
                
                // 授权按钮,截取code的值
                let queryNS = query! as NSString
                let code = queryNS.substringFromIndex(codeString.characters.count)
                
                //// 发起请求获取AccessToken
                UserModelController.sharedInstance.loadAccessToken(code)
                
            } else {
                // 取消按钮,关闭控制器
                close()
            }
            
            return false
        } else {
            // 2.不是授权回调地址,直接加载这个请求
            return true
        }
    }
}
    
    

